import React, { useState, useEffect } from 'react'
import { ArrowLeft, WapHome, WeappNav } from '@react-vant/icons'
import style from './attendance.module.css'
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs'
import { Calendar } from 'antd-mobile'
import axios from 'axios'


export default function Attendance() {

  useEffect(() => {
    // 进入页面时设置
    const html = document.documentElement;
    const oldFontSize = html.style.fontSize;
    const setRem = () => {
      const width = html.clientWidth < 750 ? 750 : html.clientWidth;
      html.style.fontSize = (width / 750) * 75 + 'px';
    };
    setRem();
    window.addEventListener('resize', setRem);

    // 离开页面时恢复
    return () => {
      window.removeEventListener('resize', setRem);
      html.style.fontSize = oldFontSize || '';
    };
  }, []);

  
    const navigate=useNavigate();
    const today = dayjs()
    const [date, setDate] = useState(today)
    const [now,setnow] = useState(dayjs())
    

  const [list, setList] = useState(() => {
    let array = localStorage.getItem('user')
    return array ? JSON.parse(array) : []
  })
  const username = list[0].username
  const [data, setData] = useState([])
  const [qingjia, setqingjia] = useState([])
  const [chuchai,setchuchai] = useState([])
  const [waiqin,setwaiqin] = useState([])
  console.log();
  
  const getdata = () => {
    axios.get(`http://localhost:3111/attendance/list?username=${username}`).then(res=>{
      setData(res.data.data)
    })
  }
  const getqingjia = () => {
    axios.get(`http://localhost:3111/attendance/qingjia?username=${username}`).then(res=>{
      console.log(res.data.data);
      setqingjia(res.data.data)
      console.log(res.data.chuchai);
      console.log(res.data.waiqin);
      setchuchai(res.data.chuchai)
      setwaiqin(res.data.waiqin)
    })
  }
  useEffect(() => {
    getqingjia()
    getdata()
  },[])

  const matchedDate = data.length > 0 
  ? data.find(item => {
      const currentDate = dayjs(date).format('YYYY-MM-DD')
      const itemDate = dayjs(item.date).format('YYYY-MM-DD')
      return currentDate === itemDate
    }) 
  : null

  // 直接使用原始时间字符串进行比较
  const morningTime = matchedDate?.morningTime;
  const eveningTime = matchedDate?.eveningTime;
  

  const isOnTime = morningTime && eveningTime && 
    morningTime <= '8:30' && 
    eveningTime >= '18:00';
  

  const isqingjia = qingjia.filter(item => {
    const currentDate = dayjs(date).format('YYYY-MM-DD')
    const itemDate = dayjs(item.date).format('YYYY-MM-DD')
    return currentDate === itemDate 
  })
  console.log(isqingjia,'isqingjia');
  

  const ischuchai = chuchai.filter(item => {
    const currentDate = dayjs(date).format('YYYY-MM-DD')
    const itemDate = dayjs(item.date).format('YYYY-MM-DD')
    return currentDate === itemDate 
  })
  console.log(ischuchai,'ischuchai');
  

  const iswaiqin = waiqin.filter(item => {
    const currentDate = dayjs(date).format('YYYY-MM-DD')
    const itemDate = dayjs(item.date).format('YYYY-MM-DD')
    return currentDate === itemDate
  })
  console.log(iswaiqin,'iswaiqin');


  return (
    <div>

        {/* 顶部 */}

        <div className={style.top}>
            <div className={style.content}>
                <div onClick={()=>{navigate(-1)}}><ArrowLeft style={{fontSize:'20px',fontWeight:'bolder'}} /></div>
                <div className={style.iconDivider}></div>
                <div onClick={()=>{navigate('/zhu')}}><WapHome style={{fontSize:'20px',fontWeight:'bolder',paddingRigth:'5px'}} /></div>
            </div>
            <h2>考勤统计</h2>
            <div className={style.content}>
                <div><WeappNav style={{fontSize:'25px',fontWeight:'bolder',paddingLeft:'5px',paddingTop:'5px'}} /></div>
                <div className={style.iconDivider}></div>
                <div><div className={style.circleBorder}>
  <div className={style.circleInner}></div>
</div></div>
            </div>

          

        </div>
          {/* 用户信息 */}
          {list.map((item,index)=>{
            return(
        <div key={item._id} className={style.profilecard}>
      <div className={style.profileheader}></div>
      <div className={style.profileinfo}>
        <div className={style.avatarwrapper}>
          <img
            className={style.avatar}
            src={item.imgs}
            alt="avatar"
          />
        </div>
        <div className={style.userinfo}>
          <div className={style.username}>{item.username}</div>
          <div className={style.userdept}>{item.bumen}</div>
        </div>
        <div className={style.userrole}>
          <button className={style.rolebtn}>
            <div className={style.rolecn}>{item.zhiye}</div>
            <div className={style.roleen}>{item.zhiye=='经理'?'Managere':'Member'}</div>
          </button>
        </div>
      </div>
    </div>
  )
})}
    {/* 考勤汇总 */}

    <div className={style.attendancesummarycard}>
      <div className={style.summarytitle}>考勤汇总</div>
      <div className={style.summarylist}>
        <div className={style.summaryitem}>
          <div className={style.summarynum} style={{ color: '#3498db' }}>{chuchai.length}</div>
          <div className={style.summarylabel}>出差</div>
        </div>
        <div className={style.summaryitem}>
          <div className={style.summarynum} style={{ color: '#f1c40f' }}>{data.length}</div>
          <div className={style.summarylabel}>请假</div>
        </div>
        <div className={style.summaryitem}>
          <div className={style.summarynum} style={{ color: '#27ae60' }}>{waiqin.length}</div>
          <div className={style.summarylabel}>外勤</div>
        </div>
      </div>
    </div>
    {/* 考勤日历 */}
    <div>
      <Calendar
        selectionMode='single' 
         // 改为 single 模式
         allowClear={false}
        max={now}
        min={dayjs(list[0].date)}
        value={date}
        onChange={val => {
         setDate(val)
         console.log(val);
         
        }}
      />
    </div>

    {/* 考勤记录 */}
    <div className={style.attendancerow} onClick={() => {
      if (!isOnTime && matchedDate) {
        // 这里添加点击事件的处理逻辑
        console.log('点击了迟到记录', matchedDate);
        // 可以添加导航或其他操作
        navigate('/attdetail', { state: { data: matchedDate } });
      }
    }}>
      <div className={style.rowleft}>
        <span className={style.rowdate}>{dayjs(date).format('YYYY-MM-DD')}</span>
        {/* 修改状态显示逻辑，加入外勤和出差判断 */}
        <span className={isOnTime ? style.rowstatus1 : style.rowstatus}>
          {isqingjia.length > 0 ? '请假' :
           ischuchai.length > 0 ? '出差' :
           iswaiqin.length > 0 ? '外勤' :
           (matchedDate ? (isOnTime ? '正常' : '迟到') : '节假日')}
        </span>
      </div>
      <div className={style.rowcenter}>
        <span className={style.rowclockicon}>🕒</span>
        <span className={style.rowtime}>
          <span className={isOnTime?style.rowtimestart1:style.rowtimestart}>
            {matchedDate?.morningTime || '暂无打卡'}
          </span>
          <span>—</span>
          <span className={style.rowtimeend}>
            {matchedDate?.eveningTime || '暂无打卡'}
          </span>
        </span>
      </div>
      <div className={style.rowright}>
        <span className={style.rowarrow}>{'>'}</span>
      </div>
    </div>


    </div>
  )
}
